package cn.frh.org.controller;

import cn.frh.basic.util.AjaxResult;
import cn.frh.basic.util.pageList;
import cn.frh.org.domain.Department;
import cn.frh.org.query.DepartmentQuery;
import cn.frh.org.service.IDepartmentService;
import cn.frh.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {


    @Autowired
    private IDepartmentService departmentService;

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Department findOne(@PathVariable("id") Long id){
        return departmentService.loadById(id);
    }

    @ApiOperation(value = "查询所有" )
    @GetMapping
    private List<Department> findAll(){
        return departmentService.loadAll();
    }

    @ApiOperation(value = "通过ID删除" )
    @DeleteMapping("/{id}")
    private AjaxResult remove(@PathVariable("id") Long id){
        try {
            departmentService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    @ApiOperation(value = "添加或者更新" )
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }
    @ApiOperation(value = "分页查询" )
    @PostMapping
    @PreAuthorize(name = "部门列表",sn = "department:list")
    public pageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }

    @ApiOperation(value = "批量删除" )
    @PatchMapping
    private AjaxResult patchRemove(@RequestBody List<Long> ids){
        try {
            departmentService.patchRemove(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    @GetMapping("/dept")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }

}
